package com.roy.controller;

import com.roy.util.ImageUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author ：楼兰
 * @date ：Created in 2021/1/14
 * @description:
 **/
@RestController
@RequestMapping("/common/")
public class LoginController {

    Logger logger = LoggerFactory.getLogger(LoginController.class);

    @PostMapping("/login")
    public Object login(String verifyCode,HttpServletRequest request){
        String sessionVerifyCode = request.getSession().getAttribute("verifyCode").toString();
        if(sessionVerifyCode.equals(verifyCode)){
            return "login";
        }else{
            return null;
        }
    }

    @PostMapping("/logout")
    public Object logout(HttpServletRequest request){
        return "logout";
    }

    @GetMapping("/verifyCode")
    public void generateImg(HttpServletRequest request,HttpServletResponse response) throws IOException {
        response.setContentType("image/jpeg");
        ImageUtil imageUtil = ImageUtil.Instance();
        ByteArrayInputStream image = imageUtil.getImage();
        request.getSession().setAttribute("verifyCode",imageUtil.getString());
        byte[] bytes = new byte[1024];
        try(ServletOutputStream out = response.getOutputStream()){
            while(image.read(bytes)!=-1){
                out.write(bytes);
            }
        }
    }
}


